#include "Audio.h"

Audio* Audio::audio;

Audio::Audio(void)
{

}


Audio::~Audio(void)
{

}


bool Audio::Init(HWND hWnd) {
  // init static
  audio = this;
  hResult = DirectSoundCreate8(NULL, &directSound8, NULL);
  if (hResult != DS_OK) {
    Log::Write(L"Create direct sound interface fail.");
    return false;
  }
  hResult = directSound8->SetCooperativeLevel(hWnd, DSSCL_PRIORITY); 
  if (hResult != DS_OK) {
    Log::Write(L"Direct sound - set cooperative level fail.");
    return false;
  }
  return true;
}


void Audio::Release() {
  directSound8->Release();
}


LPDIRECTSOUNDBUFFER8 Audio::CreateSoundBuffer(mad_pcm *pcm, 
    int &bufferSize) {

  /*Variable*/

  DSBUFFERDESC bufferdesc;
  WAVEFORMATEX waveFormat;
  LPDIRECTSOUNDBUFFER buffer = NULL;
  LPDIRECTSOUNDBUFFER8 buffer8;
  /* set up wave format */

  memset(&waveFormat, 0, sizeof(WAVEFORMATEX)); // set value
  waveFormat.cbSize = 0;
  waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  waveFormat.nChannels = pcm->channels;
  waveFormat.nSamplesPerSec = pcm->samplerate;
  waveFormat.nBlockAlign = 4; // bytes per sample per chanel
  waveFormat.nAvgBytesPerSec = waveFormat.nBlockAlign *
    waveFormat.nSamplesPerSec;
  waveFormat.wBitsPerSample = 16; 
    
  /* setup buffer descirbe */

  bufferSize = (4 * waveFormat.nAvgBytesPerSec); // 4 sec buffer
  memset(&bufferdesc, 0, sizeof(DSBUFFERDESC));
  bufferdesc.dwSize = sizeof(DSBUFFERDESC);
  bufferdesc.dwReserved = NULL;
  bufferdesc.dwBufferBytes = bufferSize; 
  bufferdesc.dwFlags =  DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY
  | DSBCAPS_GLOBALFOCUS;
  bufferdesc.lpwfxFormat = &waveFormat;
  bufferdesc.guid3DAlgorithm = DS3DALG_DEFAULT;
  hResult = directSound8->CreateSoundBuffer(&bufferdesc, &buffer, NULL);
  if (hResult != DS_OK) {
    Log::Write(L"Create sound buffer fail.");
    return NULL;
  }
  hResult = buffer->QueryInterface(
    IID_IDirectSoundBuffer8, (LPVOID*)&buffer8);
  buffer->Release();   
  if (hResult != DS_OK) {
    Log::Write(L"Create IID_IDirectSound8 fail");
    return NULL;
  }
  return buffer8;
}